package com.lxn.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

//登录检查
@Component
public class LoginCheckFilter extends ZuulFilter {
    //filter类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //值越小越先执行
    @Override
    public int filterOrder() {
        return 1;
    }
    //true则执行run方法，false不执行run方法
    @Override
    public boolean shouldFilter() {
        //拿到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        //如果请求路径/login不需要登录检查，否则需要登录检查
        if(StringUtils.hasLength(uri) && uri.endsWith("login")){
            //是登录请求
            return false;
        }
        return true;
    }
    //登录检查
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        //设置编码
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            Map<String,Object> result = new HashMap<>();    //AJAXResult
            result.put("success",false);
            result.put("msg","未登录");
            //Fastjson
            try {
                response.getWriter().print(JSON.toJSONString(result));
                //不放行
                currentContext.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
